package com.example.utility.pdf;

import com.itextpdf.kernel.colors.DeviceRgb;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.kernel.geom.PageSize;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.borders.SolidBorder;
import com.itextpdf.layout.element.Cell;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.element.Table;
import com.itextpdf.layout.properties.HorizontalAlignment;
import com.itextpdf.layout.properties.TextAlignment;
import com.itextpdf.layout.properties.UnitValue;

import java.io.IOException;


/**
 * @author 季舟
 * @Date 2024-10-22 11:49
 */
public class CHCPdfExporter {
    public static final String SummaryExamination="本次体检对象为XXX（姓名/编号），体检日期为XXXX年XX月XX日。经过全面、细致的体检，现将各项检查结果汇总并分析如下：\n" +
            "\n" +
            "一、一般状况\n" +
            "\n" +
            "受检者体重、身高处于正常范围，BMI（身体质量指数）为XX，属于XX（正常/偏瘦/超重/肥胖）体型。血压测量值为XX/XX mmHg，处于（正常/偏高/偏低）水平。心率XX次/分，节律整齐，未见异常。\n" +
            "\n" +
            "二、内科检查\n" +
            "\n" +
            "心肺听诊未见明显异常，腹部平坦，无压痛、反跳痛，肝脾未触及肿大，肠鸣音正常。神经系统检查未见异常，四肢活动自如，肌力、肌张力正常。\n" +
            "\n" +
            "三、外科检查\n" +
            "\n" +
            "皮肤、粘膜未见异常，浅表淋巴结未触及肿大。甲状腺未触及异常，胸廓对称，脊柱生理弯曲存在，四肢关节无畸形，活动自如。\n" +
            "\n" +
            "四、五官科检查\n" +
            "\n" +
            "视力：左眼XX，右眼XX，视力水平（正常/近视/远视/弱视等）。听力检查未见异常，耳、鼻、咽、喉部未见明显病变。口腔科检查：牙齿排列整齐，无龋齿，牙龈无出血、肿胀。\n" +
            "\n" +
            "五、实验室检查\n" +
            "\n" +
            "血常规：白细胞、红细胞、血小板等指标均在正常范围内，未见异常。\n" +
            "\n" +
            "尿常规：尿液颜色、透明度、酸碱度等指标均正常，未见异常。\n" +
            "\n" +
            "肝功能：谷丙转氨酶、谷草转氨酶等指标均正常，肝功能未见异常。\n" +
            "\n" +
            "肾功能：尿素氮、肌酐等指标均正常，肾功能未见异常。\n" +
            "\n" +
            "血脂：总胆固醇、甘油三酯等指标均正常，血脂水平未见异常。\n" +
            "\n" +
            "血糖：空腹血糖值为XX mmol/L，处于（正常/偏高/偏低）水平。\n" +
            "\n" +
            "六、特殊检查\n" +
            "\n" +
            "心电图检查：心律整齐，未见异常波形。\n" +
            "\n" +
            "胸部X光检查：双肺纹理清晰，未见异常阴影，心影大小、形态正常。\n" +
            "\n" +
            "腹部B超检查：肝、胆、胰、脾、肾等脏器未见异常。\n" +
            "\n" +
            "综上所述，本次体检中，受检者各项检查指标大多处于正常范围，未见明显异常。但需注意（如有异常项目，则列出具体异常及建议，如“空腹血糖偏高，建议注意饮食调节，定期复查血糖”等）。建议受检者继续保持良好的生活习惯，定期体检，以便及时发现并处理潜在的健康问题。";

    public static void main(String[] args) {
        exportPdf("output2.pdf");
    }

    public static void exportPdf(String fileName) {
        try {
            PdfWriter writer = new PdfWriter(fileName);
            // 创建一个PDF文档
            PdfDocument pdfDocument = new PdfDocument(writer);
            // 创建一个文档
            Document document = new Document(pdfDocument, PageSize.A4);
            //字体
            PdfFont chineseFont=getchineseFont();
            //背景色
            DeviceRgb cellBackgroundColor=new DeviceRgb(192, 192, 192);
            //Paragraph 1
            Paragraph p1 = new Paragraph("健康体检报告书")
                    .setFont(chineseFont)
                    .setFontSize(18)
                    .setTextAlignment(TextAlignment.CENTER)
                    .setBold();
            document.add(p1);
            //Paragraph 2
            Paragraph p2 = new Paragraph("体检编号：123")
                    .setFont(chineseFont)
                    .setFontSize(12)
                    .setTextAlignment(TextAlignment.CENTER);
            document.add(p2);
            document.add(new Paragraph("\n"));
            //Table 1
            float[] t1ColumnWidths = {15, 35, 15, 35}; // percentage
            Table t1 = new Table(UnitValue.createPercentArray(t1ColumnWidths))
                    .setWidth(UnitValue.createPercentValue(100))
                    .setTextAlignment(TextAlignment.LEFT)
                    .setHorizontalAlignment(HorizontalAlignment.CENTER);
            t1.addCell(createCell(1, 1, "姓名", chineseFont,TextAlignment.LEFT));
            t1.addCell(createCell(1, 1, "张三", chineseFont,TextAlignment.LEFT));
            t1.addCell(createCell(1, 1, "姓名", chineseFont,TextAlignment.LEFT));
            t1.addCell(createCell(1, 1, "男", chineseFont,TextAlignment.LEFT));
            t1.addCell(createCell(1, 1, "年龄", chineseFont,TextAlignment.LEFT));
            t1.addCell(createCell(1, 1, "18岁", chineseFont,TextAlignment.LEFT));
            t1.addCell(createCell(1, 1, "姓名", chineseFont,TextAlignment.LEFT));
            t1.addCell(createCell(1, 1, "13812345678", chineseFont,TextAlignment.LEFT));
            document.add(t1);
            document.add(new Paragraph("\n"));
            //Table 2
            float[] t2ColumnWidths = {40, 60}; // percentage
            Table t2 = new Table(UnitValue.createPercentArray(t2ColumnWidths))
                    .setWidth(UnitValue.createPercentValue(100))
                    .setTextAlignment(TextAlignment.CENTER)
                    .setHorizontalAlignment(HorizontalAlignment.CENTER);
            t2.addCell(createCell(1, 2, "一般情况", chineseFont,TextAlignment.LEFT,true))
                    .addCell(createCell(1, 1, "项目名称", chineseFont).setBackgroundColor(cellBackgroundColor))
                    .addCell(createCell(1, 1, "结果", chineseFont).setBackgroundColor(cellBackgroundColor))
                    .addCell(createCell(1, 1, "症状", chineseFont))
                    .addCell(createCell(1, 1, "<症状>", chineseFont))
                    .addCell(createCell(1, 1, "体温", chineseFont))
                    .addCell(createCell(1, 1, "<体温> ℃", chineseFont));
            document.add(t2);
            document.add(new Paragraph("\n"));
            //Table 10
            float[] t10ColumnWidths = {26, 20, 18, 18, 18}; // percentage
            Table t10 = new Table(UnitValue.createPercentArray(t10ColumnWidths))
                    .setWidth(UnitValue.createPercentValue(100))
                    .setTextAlignment(TextAlignment.CENTER)
                    .setHorizontalAlignment(HorizontalAlignment.CENTER);
            t10.addCell(createCell(1, 2, "<检验类型1>", chineseFont,TextAlignment.CENTER,true))
                    .addCell(createCell(1, 3, "检查日期：<检查日期1>", chineseFont,TextAlignment.CENTER,true))
                    .addCell(createCell(1, 1, "检验项目", chineseFont).setBackgroundColor(cellBackgroundColor))
                    .addCell(createCell(1, 1, "结果", chineseFont).setBackgroundColor(cellBackgroundColor))
                    .addCell(createCell(1, 1, "参考值", chineseFont).setBackgroundColor(cellBackgroundColor))
                    .addCell(createCell(1, 1, "单位", chineseFont).setBackgroundColor(cellBackgroundColor))
                    .addCell(createCell(1, 1, "标志", chineseFont).setBackgroundColor(cellBackgroundColor));
            for (int i=1;i<10;i++){
                t10.addCell(createCell(1, 1, "<项目"+i+">", chineseFont))
                        .addCell(createCell(1, 1, "<结果"+i+">", chineseFont))
                        .addCell(createCell(1, 1, "<参考值"+i+">", chineseFont))
                        .addCell(createCell(1, 1, "<单位"+i+">", chineseFont))
                        .addCell(createCell(1, 1, "<标志"+i+">", chineseFont));
            }
            document.add(t10);
            document.add(new Paragraph("\n"));
            //Table 13
            float[] t13ColumnWidths = {100}; // percentage
            Table t13 = new Table(UnitValue.createPercentArray(t13ColumnWidths))
                    .setWidth(UnitValue.createPercentValue(100))
                    .setTextAlignment(TextAlignment.CENTER)
                    .setHorizontalAlignment(HorizontalAlignment.CENTER);
            t13.addCell(createCell(1, 1, "总检综述", chineseFont,TextAlignment.LEFT,true))
                    .addCell(createCell(1, 1, SummaryExamination, chineseFont,TextAlignment.LEFT).setKeepTogether(false))
                    .addCell(createCell(1, 1, "建议", chineseFont,TextAlignment.LEFT,true))
                    .addCell(createCell(1, 1, "<建议>", chineseFont,TextAlignment.LEFT));

            document.add(t13);
            document.add(new Paragraph("\n"));
            //Paragraph 3
            Paragraph p3= new Paragraph("总检医生：<总检医生>")
                    .setFont(chineseFont)
                    .setFontSize(12)
                    .setTextAlignment(TextAlignment.RIGHT);
            document.add(p3);
            //Paragraph 4
            Paragraph p4= new Paragraph("总检日期：<总检日期>")
                    .setFont(chineseFont)
                    .setFontSize(12)
                    .setTextAlignment(TextAlignment.RIGHT);
            document.add(p4);

            // 关闭文档
            document.close();
        } catch (Exception e) {}
    }

    /**
     * 获取中文字体
     *
     * 此方法用于创建并返回一个中文字体对象，以便在PDF文档中使用
     * 选择STSong-Light字体和UniGB-UCS2-H编码方案，以支持简体中文字符
     * 使用PdfFontFactory的EmbeddingStrategy.PREFER_EMBEDDED策略，优先嵌入字体，
     * 确保在任何环境下都能正确显示中文，避免字体缺失导致的显示问题
     *
     * @return PdfFont 返回一个中文字体对象，如果创建失败则返回null
     */
    public static PdfFont getchineseFont(){
        PdfFont chineseFont = null;
        try {
            // 创建中文字体，使用STSong-Light字体和UniGB-UCS2-H编码方案
            chineseFont = PdfFontFactory.createFont("STSong-Light","UniGB-UCS2-H", PdfFontFactory.EmbeddingStrategy.PREFER_EMBEDDED);
        } catch (IOException e) {
            // 打印异常信息，便于调试和错误追踪
            e.printStackTrace();
        }
        // 返回中文字体对象，可能为null（如果创建失败）
        return chineseFont;
    }

    private static Cell createCell(int row, int column, String text, PdfFont font) {
        //.setKeepTogether(true)为了解决表格跨页分行问题
        Paragraph paragraph = new Paragraph(text)
                .setFont(font)
                .setFontSize(10)
                .setTextAlignment(TextAlignment.CENTER); // 设置文本居中对齐
        return new Cell(row, column)
                .add(paragraph)
                .setBorder(new SolidBorder(new DeviceRgb(0, 0, 0), 0.5f))
                .setKeepTogether(true);
    }

    private static Cell createCell(int row, int column, String text, PdfFont font,TextAlignment alignment) {
        //.setKeepTogether(true)为了解决表格跨页分行问题
        Paragraph paragraph = new Paragraph(text)
                .setFont(font)
                .setFontSize(10)
                .setTextAlignment(alignment); // 设置文本居中对齐
        return new Cell(row, column)
                .add(paragraph)
                .setBorder(new SolidBorder(new DeviceRgb(0, 0, 0), 0.5f))
                .setKeepTogether(true);
    }

    private static Cell createCell(int row, int column, String text, PdfFont font,TextAlignment alignment, boolean bold) {
        //.setKeepTogether(true)为了解决表格跨页分行问题
        Paragraph paragraph = new Paragraph(text)
                .setFont(font)
                .setFontSize(11)
                .setTextAlignment(alignment); // 设置文本居中对齐
        if (bold){
            paragraph.setBold();
        }
        return new Cell(row, column)
                .add(paragraph)
                .setBorder(new SolidBorder(new DeviceRgb(0, 0, 0), 0.5f))
                .setKeepTogether(true);
    }
}
